import Vue from 'vue'
import ajaxs from './modules'
// 需要的时候一次请求数据，多次使用
function vue_async_global (ajaxs) {
  const data = {}
  const computed = {}
  const methods = {}
  ajaxs.forEach(({name, ajax}) => {
    const data_name = `${name}_`

    const methods_name_async = `${name}Async`
    const methods_name_update = `${name}Update`
    data[data_name] = arguments[0].default || []

    // 获取数据
    computed[name] = function () {
      this[methods_name_async]()
      return this[data_name]
    }

    // 获取单列 promise,并请求更新数据
    methods[methods_name_async] = function (update = false) {
      let current_fun = methods[methods_name_async]
      if (current_fun._promise == null || update) {
        return methods[methods_name_update].call(this)
      }
      return current_fun._promise
    }

    // 更新获取数据，并返回promise
    methods[methods_name_update] = function () {
      return methods[methods_name_async]._promise = new Promise(async (resolve, reject) => {
        resolve(this[data_name] = await ajax())
      })
    }
  })

  return new Vue({
    data: () => data,
    computed: {
      ...computed
    },
    methods
  })
}

window.$g = Vue.prototype.$g = vue_async_global(ajaxs)
